<template>
  <div class="common-layout">
    <el-container>
<!--      <el-header></el-header>-->
      <el-main>
        <div class="address-manager">
          <h2>地址管理</h2>
          <el-button type="primary" @click="showAddAddressDialog" class="addButton">添加新地址</el-button>

          <!-- 手机端显示卡片 -->
          <div class="address-list" v-if="isMobile">
            <div v-for="(address, index) in addresses" :key="index" class="address-card">
              <div class="address-content">
                <div class="address-info">
                  <p><strong>收货人：</strong>{{ address.receiverName }}</p>
                  <p><strong>电话号码：</strong>{{ address.receiverPhone }}</p>
                  <p><strong>地址：</strong>{{ address.province }} {{ address.city }} {{ address.district }} {{ address.address }}</p>
                </div>
              </div>
              <div class="address-actions">
                <button class="btn btn-edit" @click="showEditAddressDialog(address)">修改</button>
                <button class="btn btn-delete" @click="deleteAddress(address)">删除</button>
              </div>
            </div>
          </div>

<!--          非手机端使用表格-->
          <el-table v-else :data="addresses" style="width: 100%">
            <el-table-column prop="receiverName" label="收货人"></el-table-column>
            <el-table-column prop="receiverPhone" label="电话号码"></el-table-column>
            <el-table-column prop="province" label="省份"></el-table-column>
            <el-table-column prop="city" label="城市"></el-table-column>
            <el-table-column prop="district" label="区县"></el-table-column>
            <el-table-column prop="address" label="详细地址"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="mini" @click="showEditAddressDialog(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" @click="deleteAddress(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 添加新地址的对话框 -->
          <el-dialog title="添加新地址" v-model="addAddressDialogVisible" v-bind:width="isMobile ? '90%' : '30%'" class="custom-dialog">
            <el-form :model="newAddress">
              <el-form-item label="收货人">
                <el-input v-model="newAddress.receiverName" class="inputStyle"></el-input>
              </el-form-item>
              <el-form-item label="电话号码">
                <el-input v-model="newAddress.receiverPhone"></el-input>
              </el-form-item>
              <el-form-item label="省份">
                <el-input v-model="newAddress.province"></el-input>
              </el-form-item>
              <el-form-item label="城市">
                <el-input v-model="newAddress.city"></el-input>
              </el-form-item>
              <el-form-item label="区县">
                <el-input v-model="newAddress.district"></el-input>
              </el-form-item>
              <el-form-item label="详细地址">
                <el-input v-model="newAddress.address"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="addAddressDialogVisible = false" class="cancleButton">取 消</el-button>
        <el-button type="primary" @click="addAddress" class="confirmButton">确 定</el-button>
      </span>
          </el-dialog>

          <!-- 修改地址的对话框 -->
          <el-dialog title="修改地址" v-model="editAddressDialogVisible" v-bind:width="isMobile ? '90%' : '30%'">
            <el-form :model="editAddress">
              <el-form-item label="收货人">
                <el-input v-model="editAddress.receiverName"></el-input>
              </el-form-item>
              <el-form-item label="电话号码">
                <el-input v-model="editAddress.receiverPhone"></el-input>
              </el-form-item>
              <el-form-item label="省份">
                <el-input v-model="editAddress.province"></el-input>
              </el-form-item>
              <el-form-item label="城市">
                <el-input v-model="editAddress.city"></el-input>
              </el-form-item>
              <el-form-item label="区县">
                <el-input v-model="editAddress.district"></el-input>
              </el-form-item>
              <el-form-item label="详细地址">
                <el-input v-model="editAddress.address"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="editAddressDialogVisible = false" class="cancleButton">取 消</el-button>
        <el-button type="primary" @click="updateAddress" class="confirmButton">确 定</el-button>
      </span>
          </el-dialog>
        </div>
      </el-main>
    </el-container>

  </div>

</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import axios from "axios";

const addresses = ref([]);

const newAddress = ref({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: '',
});

const editAddress = ref({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: '',
});

const addAddressDialogVisible = ref(false);
const editAddressDialogVisible = ref(false);


// 计算属性判断是否是手机端
const isMobile = computed(() => window.innerWidth <= 768);

const showAddAddressDialog = () => {
  addAddressDialogVisible.value = true;
};

const showEditAddressDialog = (address) => {
  editAddress.value = { ...address, receiverId: address.receiverId, userId: address.userId };
  editAddressDialogVisible.value = true;
};

//页面加载
onMounted(()=>{
  loadAddresses();
});

//加载地址
const loadAddresses = async () => {
  try {
    const userInfo = sessionStorage.getItem('CurUser');
    console.log('UserInfo:', userInfo); // 打印用户信息
    if (!userInfo) {
      ElMessage.error('请先登录');
      return;
    }

    const user = JSON.parse(userInfo);
    const userId = user.userId;
    console.log('UserId:', userId); // 打印用户ID

    const response = await axios.get('/dressup/order/receivers', {
      params: { userId: userId }
    });

    console.log('Response:', response.data); // 打印响应数据
    if (Array.isArray(response.data)) {
      addresses.value = response.data;
    } else {
      addresses.value = [];
      ElMessage.error('加载收货地址失败');
    }
  } catch (error) {
    console.error('Error:', error); // 打印错误信息
    ElMessage.error('加载收货地址失败，请稍后再试');
  }
};

const addAddress = async () => {
  // 检查必填项是否为空
  if (!newAddress.value.receiverName || !newAddress.value.receiverPhone || !newAddress.value.province || !newAddress.value.city || !newAddress.value.district || !newAddress.value.address) {
    ElMessage.error('请完整填写所有地址信息');
    return;
  }

  try {
    const userInfo = sessionStorage.getItem('CurUser');
    if (!userInfo) {
      ElMessage.error('请先登录');
      return;
    }

    const user = JSON.parse(userInfo);
    newAddress.value.userId = user.userId; // 设置 user_id

    const response = await axios.post('/dressup/receiver/addNewAddress', {
      userId: newAddress.value.userId,
      receiverName: newAddress.value.receiverName,
      receiverPhone: newAddress.value.receiverPhone,
      province: newAddress.value.province,
      city: newAddress.value.city,
      district: newAddress.value.district,
      address: newAddress.value.address
    });

    if (response.data) {
      addresses.value.push({ ...newAddress.value });
      ElMessage.success('新增收货地址成功');
    } else {
      ElMessage.error('新增收货地址失败');
    }
  } catch (error) {
    ElMessage.error('新增收货地址失败，请稍后再试');
  } finally {
    newAddress.value = {
      receiverName: '',
      receiverPhone: '',
      province: '',
      city: '',
      district: '',
      address: '',
      userId: '' // 重置 userId
    };
    addAddressDialogVisible.value = false;
  }

  loadAddresses();
};

const updateAddress = async () => {
  // 检查必填项是否为空
  if (!editAddress.value.receiverName || !editAddress.value.receiverPhone || !editAddress.value.province || !editAddress.value.city || !editAddress.value.district || !editAddress.value.address) {
    ElMessage.error('请完整填写所有地址信息');
    return;
  }

  try {
    console.log('Edit Address:', editAddress.value); // 打印更新地址信息

    // 确保传递的字段名与后端一致
    const updateData = {
      receiverId: editAddress.value.receiverId, // 收件人ID
      userId: editAddress.value.userId, // 用户ID
      receiverName: editAddress.value.receiverName, // 收件人姓名
      receiverPhone: editAddress.value.receiverPhone, // 收件人电话
      province: editAddress.value.province, // 省
      city: editAddress.value.city, // 市
      district: editAddress.value.district, // 区
      address: editAddress.value.address // 详细地址
    };

    console.log('Update Request Data:', updateData); // 打印请求参数

    const response = await axios.post('/dressup/receiver/updateAddress', updateData);
    console.log('Response:', response.data); // 打印响应数据

    // 根据返回的响应数据进行处理
    if (response.data === "收货地址更新成功") {
      const index = addresses.value.findIndex(
          (address) => address.receiverId === editAddress.value.receiverId
      );
      if (index !== -1) {
        addresses.value[index] = { ...editAddress.value }; // 更新地址列表中的地址
        ElMessage.success('收货地址更新成功');
      }
    } else {
      ElMessage.error('收货地址更新失败');
    }
  } catch (error) {
    console.error('Error:', error); // 打印错误信息

    if (error.response && error.response.data) {
      console.log('Error Response:', error.response.data); // 打印错误响应内容
      ElMessage.error(`收货地址更新失败: ${error.response.data.message || error.response.data.error}`);
    } else {
      ElMessage.error('收货地址更新失败，请稍后再试');
    }
  } finally {
    editAddressDialogVisible.value = false; // 关闭编辑对话框
  }
};


const deleteAddress = async (address) => {
  try {
    // 使用 DELETE 请求方法，并确保路径中的 receiverId 正确传递
    const response = await axios.delete(`/dressup/receiver/deleteAddress/${address.receiverId}`);

    console.log('Delete Response:', response.data); // 打印响应数据

    if (response.data === "收货地址删除成功") {
      const index = addresses.value.findIndex(
          (addr) => addr.receiverId === address.receiverId // 确保使用 receiverId 作为判断条件
      );
      if (index !== -1) {
        addresses.value.splice(index, 1); // 删除对应地址
        ElMessage.success('收货地址删除成功');
      }
    } else {
      ElMessage.error('收货地址删除失败');
    }
  } catch (error) {
    console.error('Error:', error); // 打印错误信息
    ElMessage.error('收货地址删除失败，请稍后再试');
  }
};

</script>

<style scoped>
:deep(.el-input) {
  --el-color-primary: #ffd2d8;
}

.address-manager {
  /*max-width: 800px;*/
  width: 90%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #fff;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

/*.el-button {*/
/*  margin-bottom: 20px;*/
/*}*/

.addButton{
  border:#ffd2d8;
  color: black;
  background-color: #ffd2d8;
}

.addButton:hover{
  transform: scale(1.05);
}

.confirmButton , .cancleButton{
  border: #ffd2d8;
  background-color: #ffd2d8;
  color: black;
}

.confirmButton:hover, .cancleButton:hover{
  transform: scale(1.05);
}

/* 响应式布局 */

/* 超小屏幕（手机，小于768px） */
@media (max-width: 767px) {
  .address-manager {
    width: 100%; /* 满屏宽度 */
    padding: 10px;
  }

  /*.el-table {*/
  /*  font-size: 12px; !* 调整字体大小 *!*/
  /*}*/

  h2 {
    font-size: 18px;
  }

  /*.el-dialog {*/
  /*  width: 90%; !* 对话框宽度适应屏幕 *!*/
  /*}*/

  .addButton, .confirmButton, .cancleButton {
    font-size: 14px; /* 按钮字体大小适应小屏幕 */
  }
}

/* 小屏幕（平板，>= 768px 和 < 992px） */
@media (min-width: 768px) and (max-width: 991px) {
  .address-manager {
    width: 80%;
    max-width: 750px; /* 最大宽度750px */
    padding: 20px;
  }

  /*.el-table {*/
  /*  font-size: 14px;*/
  /*}*/

  h2 {
    font-size: 20px;
  }

  /*.el-dialog {*/
  /*  width: 80%; !* 对话框宽度适应屏幕 *!*/
  /*}*/

  .addButton, .confirmButton, .cancleButton {
    font-size: 16px;
  }
}

/* 中等屏幕（桌面显示器，>= 992px 和 < 1200px） */
@media (min-width: 992px) and (max-width: 1199px) {
  .address-manager {
    width: 90%;
    max-width: 970px; /* 最大宽度970px */
    padding: 30px;
  }

  /*.el-table {*/
  /*  font-size: 16px;*/
  /*}*/

  h2 {
    font-size: 24px;
  }

  /*.el-dialog {*/
  /*  width: 60%; !* 更大的对话框宽度 *!*/
  /*}*/

  .addButton, .confirmButton, .cancleButton {
    font-size: 18px;
  }
}

/* 大屏幕（大桌面显示器，>= 1200px） */
@media (min-width: 1200px) {
  .address-manager {
    width: 90%;
    max-width: 1170px; /* 最大宽度1170px */
    padding: 40px;
  }

  /*.el-table {*/
  /*  font-size: 14px;*/
  /*}*/

  h2 {
    font-size: 28px;
  }

  /*.el-dialog {*/
  /*  width: 50%; !* 最大对话框宽度 *!*/
  /*}*/

  .addButton, .confirmButton, .cancleButton {
    font-size: 14px;
  }
}

/*卡片样式*/
.address-list {
  margin: 20px 0;
}

.address-card {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.address-content {
  margin-bottom: 10px;
}

.address-info p {
  margin: 5px 0;
}

.address-actions {
  display: flex;
  flex-direction: column; /* 按钮垂直排列 */
  align-items: flex-start; /* 按钮左对齐 */
}

.btn {
  width: 100%; /* 按钮宽度占满容器 */
  padding: 10px; /* 增加按钮的内边距 */
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 10px; /* 在按钮之间添加间隔 */
}

.btn-edit {
  background-color: white;
  border: 1px solid #dddddd;
  color: gray;
}

.btn-edit:hover {
  background-color: #66b1ff;
}

.btn-delete {
  background-color: #f56c6c;
  color: #fff;
}

.btn-delete:hover {
  background-color: #f78989;
}


</style>